// pages/service/buyCar.js
var $api = require('../../utils/api')
Page({

  /**
   * 页面的初始数据
   */
  data: {
    content: '', //测试用变量
    images: [], //图片上传数组
    autosize: {
      maxHeight: 80,
      minHeight: 80
    },
  },
  //文件上传
  uploadImage: function(path) {
    return new Promise(function (resolve, reject) {
      $api.upLoad(path).then(res => {
        let resData = JSON.parse(res);
        if (resData.code == 1) {
          resolve(resData.data.url) ;
        }
      })
     })
  },
  afterRead: function (event) {
    const files = event.detail.file;
    for (var index in files) {
      this.uploadImage(files[index].path).then(res => {
        let images = this.data.images;
        images.push({url : res})
        this.setData({
          images
        })
      }).catch(err => {  //请求失败
        console.log(err);
      });
    };
  },
  //图片上传前
  beforeRead(event) {
    const {
      file,
      callback
    } = event.detail;
    callback(file.type === 'image');
  },
  //删除上传
  delete: function (event) {
    let imgDelIndex = event.detail.index;
    let fileList = this.data.fileList;
    fileList.splice(imgDelIndex, 1);
    this.setData({
      fileList
    })
  },
  //删除上传
  delete: function (event) {
    let imgDelIndex = event.detail.index;
    let images = this.data.images;
    images.splice(imgDelIndex, 1);
    this.setData({
      images
    })
  },

  //发表求购
  submit: function () {
    if (this.data.content == '') {
      wx.showToast({
        title: '请输入内容后提交!',
        icon: 'none',
        duration: 2000 //持续的时间
      })
    } else {
      let img_arr = '';
      if (this.data.images.length > 0) {
        for (let i = 0; i < this.data.images.length; i++) {
          img_arr += this.data.images[i].url + ','
        }
        //去除最后一个逗号
        let reg = /,$/gi;
        img_arr = img_arr.replace(reg, "");
      }
      let params = {
        status: 0,
        images: img_arr,
        phone: wx.getStorageSync('user_phone'),
        content: this.data.content
      };
      $api.buyingMessage(params).then(res => {
        if (res.code == 1) {
          wx.navigateBack({
            delta: 1,
            success: function () {
              wx.showToast({
                title: '提交成功!',
                icon: 'none',
                duration: 2000 //持续的时间
              })
            }
          })
        }
      })
    }
  },



  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})